/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.session;

import com.inspur.edp.cef.api.RefObject;
import io.iec.edp.caf.commons.layeringcache.cache.Cache;
import io.iec.edp.caf.commons.layeringcache.manager.CacheManager;
import io.iec.edp.caf.commons.layeringcache.setting.LayeringCacheSetting;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

public class TokenSessionMappingCacheManger {

  private TokenSessionMappingCacheManger() {
  }

  public static TokenSessionMappingCacheManger getInstance() {
    return instance;
  }

  private static final String cacheName = "BefTokenSessionMapping";

  private static volatile TokenSessionMappingCacheManger instance = new TokenSessionMappingCacheManger();
  private volatile Cache cache;
  private static Object createCacheLock = new Object();

  public Cache getCache() {
    if (cache == null) {
      synchronized (createCacheLock) {
        if (cache == null) {
          cache = createCache();
        }
      }
    }
    return cache;
  }

  private Cache createCache() {
    CacheManager mgr = SpringBeanUtils.getBean(CacheManager.class);
    LayeringCacheSetting setting = new LayeringCacheSetting.Builder().disableFirstCache()
        .enableSecondCache().secondCacheExpireTime(12).secondCacheTimeUnit(TimeUnit.HOURS)
        .depict(cacheName).build();
    return mgr.getCache(cacheName, setting);
  }

  public List<String> getAndEvict(String token, RefObject<String> su) {
    Objects.requireNonNull(token);
    List<String> rez = getCache().get(token, List.class);
    //TODO: 广水临时处理, 支持高可靠性后移除
    if(rez != null && !rez.isEmpty()) {
      String suStr = rez.get(0);
      if(suStr != null && suStr.length() != 36) {
        su.argvalue = suStr;
        rez.remove(0);
      }
    }
    getCache().evict(token);
    return rez;
  }

  public void set(String token, List<String> value) {
    Objects.requireNonNull(token);
    getCache().put(token, value);
  }

  public void evict(String token) {
    Objects.requireNonNull(token);
    getCache().evict(token);
  }
}
